<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-09-22 16:03:55
 * @Description: 减灾中心外协任务发布系统
-->
<template>
    <div class="task-publish-container">
      <el-card class="header-card">
        <template #header>
          <div class="card-header">
            <span class="title">减灾中心外协任务发布系统</span>
            <el-button type="primary" @click="showTaskForm = true">
              <el-icon><Plus /></el-icon>
              发布新任务
            </el-button>
          </div>
        </template>
        
        <!-- 任务查询组件 -->
        <TaskSearch 
          :personnel-list="personnelList"
          @search="handleSearch" 
          @reset="handleReset" 
        />
      </el-card>
  
      <!-- 任务列表组件 -->
      <el-card class="list-card">
        <TaskList 
          :tasks="filteredTasks" 
          :loading="loading"
          @edit="handleEditTask"
          @delete="handleDeleteTask"
          @view="handleViewTask"
          @status-change="handleStatusChange"
          @duplicate="handleDuplicateTask"
        />
      </el-card>
  
      <!-- 任务表单弹窗 -->
      <TaskForm 
        v-model="showTaskForm"
        :task="currentTask"
        :personnel-list="personnelList"
        @save="handleSaveTask"
        @cancel="handleCancelTask"
      />
  
      <!-- 任务详情弹窗 -->
      <TaskDetail
        v-model="showTaskDetail"
        :task="currentTask"
        :personnel-list="personnelList"
        @close="showTaskDetail = false"
        @edit="handleEditTask"
      />
    </div>
  </template>
  
  <script setup lang="ts">
  import { defineComponent, reactive, ref, toRefs, onMounted, watch, computed } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { Plus } from '@element-plus/icons-vue';
  // 导入子组件（实际项目中需要根据文件结构调整路径）
  import TaskSearch from './TaskSearch.vue';
  import TaskList from './TaskList.vue';  
  import TaskForm from './TaskForm.vue';
  import TaskDetail from './TaskDetail.vue';

  // 接口定义
  interface PersonnelInfo {
    index: number;
    personnelCategory: string;
    department: string;
    name: string;
    gender: string;
    education: string;
    degree: string;
    graduatedFrom: string;
    personnelNature: string;
    workContent: string;
    workLocation: string;
    entryDate: string;
    contractStartDate: string;
    contractEndDate: string;
  }
  
  interface TaskInfo {
    id: string;
    title: string;
    description: string;
    assignedTo: string[];
    assignedToNames: string[];
    status: 'pending' | 'in-progress' | 'completed' | 'cancelled';
    priority: 'low' | 'medium' | 'high' | 'urgent';
    createdAt: string;
    deadline: string;
    department: string;
    taskType: string;
    attachments?: string[];
    remarks?: string;
  }
  
  interface SearchParams {
    title?: string;
    status?: string;
    assignedTo?: string;
    department?: string;
    priority?: string;
    dateRange?: [string, string];
  }
  
  // 响应式数据
  const loading = ref(false);
  const showTaskForm = ref(false);
  const showTaskDetail = ref(false);
  const currentTask = ref<TaskInfo | null>(null);
  const personnelList = ref<PersonnelInfo[]>([]);
  const taskList = ref<TaskInfo[]>([]);
  const searchParams = ref<SearchParams>({});
  
  // 计算属性 - 过滤后的任务列表
  const filteredTasks = computed(() => {
    let filtered = taskList.value;
    
    if (searchParams.value.title) {
      filtered = filtered.filter(task => 
        task.title.toLowerCase().includes(searchParams.value.title!.toLowerCase())
      );
    }
    
    if (searchParams.value.status) {
      filtered = filtered.filter(task => task.status === searchParams.value.status);
    }
    
    if (searchParams.value.assignedTo) {
      filtered = filtered.filter(task => 
        task.assignedTo.includes(searchParams.value.assignedTo!)
      );
    }
    
    if (searchParams.value.department) {
      filtered = filtered.filter(task => task.department === searchParams.value.department);
    }
    
    if (searchParams.value.priority) {
      filtered = filtered.filter(task => task.priority === searchParams.value.priority);
    }
    
    if (searchParams.value.dateRange && searchParams.value.dateRange[0] && searchParams.value.dateRange[1]) {
      filtered = filtered.filter(task => {
        const createdAt = new Date(task.createdAt);
        const start = new Date(searchParams.value.dateRange![0]);
        const end = new Date(searchParams.value.dateRange![1]);
        return createdAt >= start && createdAt <= end;
      });
    }
    
    return filtered;
  });
  
  // 视窗高度响应式
  const view = reactive({
    height: window.innerHeight,
  });
  
  // 窗口大小变化处理
  window.onresize = () => {
    view.height = window.innerHeight;
  };
  
  // 加载人员数据
  const loadPersonnelData = () => {
    loading.value = true;
    
    setTimeout(() => {
      const rawData = [
        [
          "index", 1,
          "personnelCategory", "劳务派遣人员",
          "department", "中心综合办公室",
          "name", "安易",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "美国俄勒冈大学",
          "personnelNature", "业务秘书",
          "workContent", "研究生院相关工作，科普宣传",
          "workLocation", "中国水科院",
          "entryDate", "2024-06-01",
          "contractStartDate", "2024-06-01",
          "contractEndDate", "2026-05-31"
        ],
        [
          "index", 2,
          "personnelCategory", "劳务派遣人员",
          "department", "中心综合办公室",
          "name", "费添",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "安徽农业大学",
          "personnelNature", "业务秘书",
          "workContent", "主要负责日常收发文处理、党建相关工作，协助中心会务安排，以及领导安排的其他工作。",
          "workLocation", "中国水科院",
          "entryDate", "2024-08-01",
          "contractStartDate", "2024-08-01",
          "contractEndDate", "2026-07-31"
        ],
        [
          "index", 3,
          "personnelCategory", "劳务派遣人员",
          "department", "减灾所工程部",
          "name", "严杰",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "临沂大学",
          "personnelNature", "科研助理",
          "workContent", "进行山东省小型水库雨水工情自动测报和水库安全运行及防洪调度项目（包9）的1763座小水库及143条河流的验收准备工作和汇交材料。为小型水库雨水工情自动测报和水库安全运行及防洪调度项目其他项目组提供技术支持。",
          "workLocation", "外地驻场",
          "entryDate", "2022-06-01",
          "contractStartDate", "2024-06-01",
          "contractEndDate", "2026-05-31"
        ],
        [
          "index", 4,
          "personnelCategory", "劳务派遣人员",
          "department", "减灾所抗旱部",
          "name", "梁尹超",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "中国石油大学（华东）",
          "personnelNature", "业务秘书",
          "workContent", "事务性工作，主要负责部门项目招投标标书内的商务类收集与编写、项目申报与合同的申请、甲乙双方单位的对接工作，专利、软著、报奖、院章等的申请并盖章；财务报销核对与填报、项目支付进度的督促和结算。协助完成项目任务书、实施方案、工作报告、验收申请及技术报告撰写，项目初验材料打印、核对及盖章等。部门招收学生和联合培养学生的劳务签订等事宜，项目材料归档、部门工会奖品发放、会议材料的收纳以及快递的收发等。",
          "workLocation", "中国水科院",
          "entryDate", "2013-10-01",
          "contractStartDate", "2023-10-02",
          "contractEndDate", "2025-10-01"
        ],
        [
          "index", 5,
          "personnelCategory", "劳务派遣人员",
          "department", "减灾所工程部",
          "name", "张珊",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "邢台学院",
          "personnelNature", "业务秘书",
          "workContent", "主要负责项目管理、财务管理、审计方面工作，项目管理方面包括项目投标、合同签订、项目实施、验收及归档、外协合同前期材料准备及合同签订、管理、验收等工作，财务管理方面包括职工差旅、会议等报销以及筹备会议、报奖、专利软著申请等工作。审计方面包括根据审计要求统计项目材料，走流程盖章等工作。另外负责部门统计工作，包括院内通知、中心通知等汇总工作。",
          "workLocation", "中国水科院",
          "entryDate", "2022-11-01",
          "contractStartDate", "2024-11-01",
          "contractEndDate", "2026-10-31"
        ],
        [
          "index", 6,
          "personnelCategory", "劳务派遣人员",
          "department", "减灾所洪管部",
          "name", "常晓艳",
          "gender", "女",
          "education", "大学专科",
          "degree", "",
          "graduatedFrom", "河南安阳职业学院",
          "personnelNature", "业务秘书",
          "workContent", "主要负责主合同和外协合同的签定、经费收支开票，合同验收；配合召开项目各种会议的召开及报销；负责部门同事日常费用及差旅的报销填报工作，购买办公用品；部分纵向项目的预算编制；投标项目的标书制作。配合上级部门做好各项检查、审计、各种表格的填报，项目归档工作等。",
          "workLocation", "中国水科院",
          "entryDate", "2022-04-01",
          "contractStartDate", "2024-04-01",
          "contractEndDate", "2026-03-31"
        ],
        [
          "index", 7,
          "personnelCategory", "劳务派遣人员",
          "department", "减灾所工程部",
          "name", "田相彩",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "北京工商大学",
          "personnelNature", "科研助理",
          "workContent", "主要从事水土保持与山洪灾害防治相关工作。参与了水利部生产建设项目水土保持监管遥感解译与判别项目的遥感解译、合规性判读、成果数据分析、项目总结报告等工作，参与了陕西省2024、2025年度山洪灾害防治项目的投标、平台测试、项目周报日报、成果报告的撰写等工作，整理了往年陕西项目的相关资料及归档工作，此外参与了山洪气象预警值班、智能解译等工作。",
          "workLocation", "中国水科院",
          "entryDate", "2024-04-01",
          "contractStartDate", "2024-04-01",
          "contractEndDate", "2026-03-31"
        ],
        [
          "index", 8,
          "personnelCategory", "劳务派遣人员",
          "department", "减灾所技术部",
          "name", "付雪",
          "gender", "女",
          "education", "大学本科",
          "degree", "学士学位",
          "graduatedFrom", "北京科技大学",
          "personnelNature", "业务秘书",
          "workContent", "(1)财务报销：填单、制单、签字、送单等工作。\n(2)会议组织：负责组织内部或外部学术、技术等类型会议；专家接待；会议纪要。\n(3)投标工作：负责商务标书撰写等招投标工作。\n(4)团队管理：协助团队项目和人员管理，如归档、内审、考勤记录等工作。\n(5)其他工作：团队交办的其他任务。",
          "workLocation", "中国水科院D座231",
          "entryDate", "2024-10-01",
          "contractStartDate", "2024-10-01",
          "contractEndDate", "2026-09-30"
        ]
      ];
  
      // 转换数据格式
      personnelList.value = rawData.map(arr => {
        const obj: any = {};
        for (let i = 0; i < arr.length; i += 2) {
          obj[arr[i]] = arr[i + 1];
        }
        return obj as PersonnelInfo;
      });
  
      // 初始化一些示例任务数据
      initSampleTasks();
      
      loading.value = false;
    }, 1000);
  };
  
  // 初始化示例任务数据
// 初始化示例任务数据（扩充版）
const initSampleTasks = () => {
  taskList.value = [
    {
      id: '1',
      title: '水库安全监测数据分析',
      description: '负责分析山东省小型水库监测数据，包括水位、流量等关键指标的统计分析，并编制相关技术报告',
      assignedTo: ['李明', '王小红'],
      assignedToNames: ['李明', '王小红'],
      status: 'in-progress',
      priority: 'high',
      createdAt: '2025-09-18',
      deadline: '2025-10-15',
      department: '减灾所工程部',
      taskType: '数据分析',
      attachments: ['监测数据.xlsx', '技术要求.pdf'],
      remarks: '发起人：张主任，岗位要求：科研助理，申请人员：李明、王小红、赵强'
    },
    {
      id: '2',
      title: '防洪调度系统优化',
      description: '优化现有防洪调度系统的算法模块，提升计算效率和预警准确性，包括前端界面改进和后端逻辑优化',
      assignedTo: [],
      assignedToNames: [],
      status: 'pending',
      priority: 'high',
      createdAt: '2025-09-17',
      deadline: '2025-11-30',
      department: '减灾所技术部',
      taskType: '系统开发',
      attachments: ['系统架构图.png', '需求文档.docx', '测试数据.sql'],
      remarks: '发起人：陈工程师，岗位要求：技术开发，申请人员：张技术、刘开发'
    },
    {
      id: '3',
      title: '年度工作总结材料整理',
      description: '整理2025年度减灾中心各部门工作总结材料，编制综合报告，协调各部门数据收集和格式统一',
      assignedTo: ['王秘书'],
      assignedToNames: ['王秘书'],
      status: 'completed',
      priority: 'medium',
      createdAt: '2025-09-10',
      deadline: '2025-09-30',
      department: '中心综合办公室',
      taskType: '文档整理',
      attachments: ['模板.docx'],
      remarks: '发起人：李部长，岗位要求：业务秘书，申请人员：王秘书'
    },
    {
      id: '4',
      title: '气象预警模型验证',
      description: '对新开发的气象预警模型进行历史数据验证，分析模型准确率，优化参数配置，编写验证报告',
      assignedTo: ['孙研究'],
      assignedToNames: ['孙研究'],
      status: 'in-progress',
      priority: 'high',
      createdAt: '2025-09-20',
      deadline: '2025-10-20',
      department: '减灾所技术部',
      taskType: '模型验证',
      attachments: ['历史数据.csv', '模型文档.pdf'],
      remarks: '发起人：赵研究员，岗位要求：科研助理，申请人员：孙研究、钱助理'
    },
    {
      id: '5',
      title: '设备采购清单制作',
      description: '制作2026年度设备采购清单，包括预算编制、供应商调研、技术参数确认等工作',
      assignedTo: [],
      assignedToNames: [],
      status: 'pending',
      priority: 'medium',
      createdAt: '2025-09-22',
      deadline: '2025-10-25',
      department: '中心综合办公室',
      taskType: '采购管理',
      attachments: [],
      remarks: '发起人：周主管，岗位要求：业务秘书，需要人数：1人'
    },
    {
      id: '6',
      title: '洪水风险评估报告',
      description: '基于最新的洪水模型和历史数据，编制华北地区洪水风险评估报告，包括风险等级划分和防御建议',
      assignedTo: [],
      assignedToNames: [],
      status: 'pending',
      priority: 'urgent',
      createdAt: '2025-09-21',
      deadline: '2025-12-15',
      department: '减灾所洪管部',
      taskType: '风险评估',
      attachments: ['数据清单.xlsx', '技术规范.pdf'],
      remarks: '发起人：吴教授，岗位要求：科研助理，需要人数：2人，申请人员：马研究、朱助理、徐工程师'
    },
    {
      id: '7',
      title: '会议筹备和组织',
      description: '筹备2025年减灾技术交流会，包括场地预订、专家邀请、材料准备、会务安排等全流程服务',
      assignedTo: ['高秘书'],
      assignedToNames: ['高秘书'],
      status: 'in-progress',
      priority: 'medium',
      createdAt: '2025-09-15',
      deadline: '2025-11-10',
      department: '中心综合办公室',
      taskType: '会议组织',
      attachments: ['会议议程.docx', '专家名单.xlsx'],
      remarks: '发起人：胡经理，岗位要求：业务秘书，申请人员：高秘书、任助理'
    },
    {
      id: '8',
      title: '监测平台数据迁移',
      description: '将旧版监测平台的历史数据迁移到新系统，确保数据完整性和准确性，编写迁移脚本和测试方案',
      assignedTo: ['程开发'],
      assignedToNames: ['程开发'],
      status: 'completed',
      priority: 'high',
      createdAt: '2025-09-05',
      deadline: '2025-09-25',
      department: '减灾所技术部',
      taskType: '数据迁移',
      attachments: ['数据库结构.sql', '迁移方案.docx'],
      remarks: '发起人：郭工程师，岗位要求：技术开发，申请人员：程开发'
    }
  ];
};
  
  // 事件处理方法
  const handleSearch = (params: SearchParams) => {
    searchParams.value = { ...params };
  };
  
  const handleReset = () => {
    searchParams.value = {};
  };
  
  const handleEditTask = (task: TaskInfo) => {
    currentTask.value = { ...task };
    showTaskForm.value = true;
  };
  
  const handleDeleteTask = async (task: TaskInfo) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除任务"${task.title}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
      
      const index = taskList.value.findIndex(t => t.id === task.id);
      if (index > -1) {
        taskList.value.splice(index, 1);
        ElMessage.success('任务删除成功');
      }
    } catch {
      // 用户取消删除
    }
  };
  
  const handleViewTask = (task: TaskInfo) => {
    currentTask.value = task;
    showTaskDetail.value = true;
  };
  
  const handleSaveTask = (task: TaskInfo) => {
    if (task.id) {
      // 编辑现有任务
      const index = taskList.value.findIndex(t => t.id === task.id);
      if (index > -1) {
        taskList.value[index] = task;
        ElMessage.success('任务更新成功');
      }
    } else {
      // 新增任务
      task.id = Date.now().toString();
      task.createdAt = new Date().toISOString().split('T')[0];
      taskList.value.unshift(task);
      ElMessage.success('任务发布成功');
    }
    
    showTaskForm.value = false;
    currentTask.value = null;
  };
  
  const handleCancelTask = () => {
    showTaskForm.value = false;
    currentTask.value = null;
  };
  
  const handleStatusChange = (task: TaskInfo, newStatus: string) => {
    const index = taskList.value.findIndex(t => t.id === task.id);
    if (index > -1) {
      taskList.value[index].status = newStatus as TaskInfo['status'];
      ElMessage.success('任务状态更新成功');
    }
  };
  
  const handleDuplicateTask = (task: TaskInfo) => {
    const newTask = {
      ...task,
      id: undefined,
      title: `${task.title} (副本)`,
      status: 'pending' as const,
      createdAt: undefined
    };
    currentTask.value = newTask;
    showTaskForm.value = true;
  };
  
  onMounted(() => {
    loadPersonnelData();
  });
  </script>
  
  <style lang="scss" scoped>
  .task-publish-container {
    padding: 20px;
    min-height: 100vh;
    background-color: #f5f5f5;
  }
  
  .header-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 20px;
        font-weight: bold;
        color: #000;
      }
    }
  }
  
  .list-card {
    min-height: 500px;
  }
  </style>
  
  <style lang="scss">
  .el-card__body {
    padding: 20px;
  }
  </style>